<?php

namespace app\api\service;

use app\api\job\NoticeJob;
use app\api\model\App;
use app\api\model\Device;
use app\api\model\Order as OrderModel;
use think\facade\Db;
use think\facade\Log;
use think\facade\Queue;

class OrderService
{


    public function callback(Device $device, $payType, $amount, $time = null)
    {
        Db::transaction(function() use ($device, $payType, $amount, $time) {
            $order = $this->findOrder($payType, $amount, $device->id,$time);
            if (!$order) {
                throw new \Exception('订单不存在');
            }
            $order->pay_time = date('Y-m-d H:i:s', time());
            $order->status = OrderModel::ORDER_STATUS_PAIED;
            $order->device_id = $device->id;
            $order->save();
            Queue::push(NoticeJob::class, ['id' => $order->id]);
        });
    }


    private function findOrder($payType, $amount,$deviceId, $time = null)
    {
        $ctime =  date('Y-m-d H:i:s',$time ?: time() );
        return OrderModel::where('pay_type', $payType)
            ->where('status', OrderModel::ORDER_STATUS_NOPAY)
            ->where('device_id', $deviceId) 
            ->where('amount', $amount)
            ->where('create_time','<=', $ctime)
            ->where('expire_time', '>=',  $ctime )
            ->find();
    }


    public function createOrder(App $app, $amount, $payType, $tradeNo, $deviceId){
      
        $timeout = $app->timeout;
       
        $lastOrder = $this->getLastOrder($amount, $payType, $deviceId); 
        if(!empty($lastOrder)){
            $conflict = $app->conflict;
            $amount += intval($conflict) === 1 ? 0.01 : -0.01;
        }

        $data = [
                'appid' => $app->appid,
                'trade_no' => $tradeNo,
                'amount' => $amount,
                'status' => OrderModel::ORDER_STATUS_NOPAY,
                'expire_time'=> date('Y-m-d H:i:s', time() + $timeout *60),
                'pay_type' => $payType,
                'order_no' => date('YmdHis') . mt_rand(1000, 9999),
                'device_id' => $deviceId,
        ];
        
        return OrderModel::create($data);
    }

    protected function getLastOrder( $amount, $payType, $deviceId){
        $lastOrder = OrderModel::where('amount', $amount)
        ->where('pay_type', $payType)
        ->where('expire_time', '>=', date('Y-m-d H:i:s', time()))
        ->where('status', OrderModel::ORDER_STATUS_NOPAY)
        ->where('device_id', $deviceId) 
        ->order('id', 'desc')
        ->find();
        return $lastOrder;
    }



    public function closeOrder($appid, $tradeNo){
        $order = OrderModel::where('trade_no', $tradeNo)
        ->where('status', OrderModel::ORDER_STATUS_NOPAY)
        ->where('appid', $appid)    
        ->find();
        if(empty($order)){
            return;
        }
        $order->status = OrderModel::ORDER_STATUS_CLOSED;
        $order->save();
    }

}